<?php
namespace app\index\controller;


use app\common\controller\FrontBase;
use app\common\service\Cart as CartService;
use app\common\service\Product as ProductService;
use app\common\tool\Tool;
use think\Request;

class Cart extends FrontBase{

    public function index(){
        $cartService = new CartService();
        $cart = $cartService->allByUser($this->user->id);
        $cart = collection($cart)->toArray();

        $productIds = [];
        foreach($cart as $key => $val ){
            $productIds[] = $val['product_id'];
        }

        //找到这些产品的信息
        $productService = new ProductService();
        $products = $productService -> all($productIds);
        $products = collection($products)->toArray();
        $products = Tool::changeArrayKey($products);

        $this->param['products'] = $products;
        $this->param['cart'] = $cart;

        return view('',$this->param);
    }


    /**
     *  增加一个到购物车
     * 添加购物车
     */
    public function addOne(Request $request){
        if(!$request->isPost()){
            $this->error("非法访问");
        }
        $id = $request ->param("id");

        $cartService = new CartService();
        $result = $cartService->addOne($id,$this->user->id);

        $this->success("操作成功");

    }

    /**
     * 从购物车中减去一个
     * @param Request $request
     */
    public function subOne(Request $request){
        if(!$request->isPost()){
            $this->error("非法访问");
        }
        $id = $request ->param("id");

        $cartService = new CartService();
        $result = $cartService->subOne($id,$this->user->id);

        $this->success("操作成功");
    }


    /**
     * 删除一个
     * id 购物车主键
     */
    public function deleteOne(Request $request){
        if(!$request->isPost()){
            $this->error("非法访问");
        }
        $id = $request ->param("id");

        $cartService = new CartService();
        $count = $cartService->delete([$id]);
        if($count){
            $this->success("操作成功");
        }
        $this->success("操作失败");
    }

    /**
     * 下单
     */
    public function order(Request $request){

        $cartService = new CartService();
        $cart = $cartService->allByUser($this->user->id);
        $cart = collection($cart)->toArray();

        $productIds = [];
        foreach($cart as $key => $val ){
            $productIds[] = $val['product_id'];
        }

        //找到这些产品的信息
        $productService = new ProductService();
        $products = $productService -> all($productIds);
        $products = collection($products)->toArray();
        $products = Tool::changeArrayKey($products);

        $total = 0;
        foreach($cart as $key => $val ){
            $current = $val['num'] * $products[$val['product_id']]['price'];
            $total += $current;
        }

        $this->param['total'] = $total;

        return view('',$this->param);
    }
}